var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var ejs = require('ejs');
var router = express.Router();
//连接MySQL数据库
var client = mysql.createConnection({
  host: 'localhost',
  port:"3306",
  user: 'root',
  password: 'weigang2004',
  database: 'test'
});

//显示图书列表
router.get('/', function (request, response) {
  console.log(request.body);
  client.query('select * from user', function (error, results) {
      response.render('user/user-list.ejs', {
          data: results
      });
  });
});


router.get('/edit/:id', function (request, response) {
  console.log(request.params.id);
  client.query('select * from user where id =?', [
      request.params.id
  ], function (error, result) {
      console.log(result);
      response.render('user/user-edit.ejs', {
          data: result[0]
      });
  });
});

//添加图书页面
router.get('/insert', function (request, response) {
  //读取模板文件
  response.render('user/user-add.ejs');
});

//添加图书处理逻辑
router.post('/insert', function (request, response) {
  //声明body
  var body = request.body;
  //执行SQL语句
  client.query('insert into user (username, nikename, password) VALUES (?, ?, ?)', [
       body.username, body.nikename, body.password
  ], function () {
       //响应信息
       response.redirect('/user');
  });
});


router.post('/edit/:id', function (request, response) {
  //声明body
  var body = request.body;
  console.log(body);
  //执行SQL语句
  client.query('update user set nikename=? where username=?',
     [body.nikename, body.username], function () {
       //响应信息
       response.redirect('/user');
  });
});

router.get('/delete/:id', function (request, response) {
  //执行SQL语句
  client.query('delete from user where id=?', [request.params.id], function () {
       //响应信息
       response.redirect('/user');
  });
});

module.exports = router;
